import AntIcon, { SearchOutlined } from '@ant-design/icons';
import { useDocumentConsumer } from '@app-cad/common/providers/documentProvider';
import {
  ConfigProvider,
  Image,
  Input,
  InputRef,
  Modal,
  Spin,
  Table,
  Tabs,
} from 'antd';
import type { TableRowSelection } from 'antd/es/table/interface';
import React, { useEffect, useRef, useState } from 'react';
import { ReactComponent as PartIcon } from '../icons/part.svg';
import { ReactComponent as ProductIcon } from '../icons/product.svg';
import './InsertDocModal.scss';
import { httpApi } from '@app-base/server';
import { getDocOriginalKey } from '@amcax/base';

interface DocModalProps {
  open: boolean;
  title: string;
  okText: string;
  rowSelectionType: 'checkbox' | 'radio';
  onOk: (selectedRows: CadDocument.FullDocumentInfo[]) => Promise<void>;
  onClose: VoidFunction;
}

const DocModal: React.FC<DocModalProps> = ({
  open,
  title,
  okText,
  rowSelectionType,
  onOk,
  onClose,
}) => {
  const { docTree } = useDocumentConsumer();
  const [loading, setLoading] = useState(false);
  const inputRef = useRef<InputRef>(null);
  const [documentList, setDocumentList] = useState<CadDocument.DocumentList>({
    personalWorkspace: [],
    projectDirectory: [],
  });
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedRows, setSelectedRows] = useState<
    CadDocument.FullDocumentInfo[]
  >([]);

  const treeIconMap = {
    product: ProductIcon,
    part: PartIcon,
  };
  const typeMap = {
    product: '产品',
    part: '零件',
  };

  useEffect(() => {
    if (open && inputRef.current) {
      setLoading(true);
      httpApi
        .getDocuments(docTree.documentInfo.collectionId, true, {
          ref: true,
          pid: getDocOriginalKey(docTree.key),
          pv: docTree.documentInfo.versionDetailResultVo.version,
        })
        .then(({ data }) => {
          setDocumentList(data);
          setLoading(false);
        });

      setSelectedRows([]);
      setTimeout(() => inputRef.current?.focus(), 0);
    }
  }, [open, docTree]);

  const columns = [
    {
      title: '文档名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, row: CadDocument.FullDocumentInfo) => (
        <div className='flex items-center'>
          {(row.thumbnail || treeIconMap[row.type]) && (
            <div
              className='doc-thumbnail-for-doc-insertion w-[60px] h-[36px] rounded-[3px] mr-4 bg-[#f8f8f8] border-[1px] text-center'
              onClick={(event) => event.stopPropagation()}
            >
              {row.thumbnail ? (
                <Image
                  className='aspect-[5/3]'
                  alt={text}
                  src={row.thumbnail}
                  preview={{ getContainer: false }}
                />
              ) : (
                <AntIcon
                  className='text-3xl'
                  component={treeIconMap[row.type]}
                />
              )}
            </div>
          )}
          {text}
        </div>
      ),
    },
    {
      title: '文档类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => typeMap[type] || type,
    },
    {
      title: '版本',
      dataIndex: ['latestVersion', 'version'],
      key: 'version',
      render: (version: number) => `v${version}`,
    },
  ];

  const isDocDisabled = (doc: CadDocument.FullDocumentInfo) =>
    !(doc.type in typeMap) ||
    (doc.documentRefResultVO && !doc.documentRefResultVO.enable);

  const rowSelection: TableRowSelection<CadDocument.FullDocumentInfo> = {
    type: rowSelectionType,
    selectedRowKeys: selectedRows.map((doc) => doc.documentUuid),
    onChange: (_, docs) => setSelectedRows(docs),
    getCheckboxProps: (doc) => ({
      disabled: isDocDisabled(doc),
    }),
  };

  const rowClassName = (doc: CadDocument.FullDocumentInfo) =>
    isDocDisabled(doc) ? 'text-gray-300 cursor-not-allowed' : '';

  const onRow = (doc: CadDocument.FullDocumentInfo) => ({
    onClick: () => {
      if (!isDocDisabled(doc)) {
        if (rowSelectionType === 'radio') {
          setSelectedRows([doc]);
          return;
        }

        setSelectedRows((prev) =>
          prev.includes(doc) ? prev.filter((d) => d !== doc) : [...prev, doc],
        );
      }
    },
  });

  const getTable = (documentInfos: CadDocument.FullDocumentInfo[]) => (
    <Table
      rowSelection={rowSelection}
      columns={columns}
      dataSource={documentInfos.filter((doc) =>
        doc.name.toLowerCase().includes(searchTerm.toLowerCase()),
      )}
      pagination={false}
      rowKey='documentUuid'
      rowClassName={rowClassName}
      onRow={onRow}
      scroll={{ y: 480 }}
    />
  );

  const docTabData = [
    {
      key: 'personalWorkspace',
      label: '个人工作区',
      children: getTable(documentList.personalWorkspace),
    },
  ];

  const handleOk = async () => {
    setLoading(true);
    await onOk(selectedRows);
    setLoading(false);
    onClose();
  };

  return (
    <ConfigProvider
      locale={{
        locale: 'zh_CN',
        Image: {
          preview: '预览',
        },
      }}
      theme={{
        components: {
          Table: {
            rowSelectedHoverBg: '#e8e8f8',
            rowSelectedBg: '#f2f2ff',
          },
        },
      }}
    >
      <Modal
        open={open}
        closable={!loading}
        width='75%'
        title={title}
        onOk={handleOk}
        okText={okText}
        okButtonProps={{ disabled: !selectedRows.length }}
        confirmLoading={loading}
        onCancel={onClose}
        cancelText='取消'
        cancelButtonProps={{ disabled: loading }}
        maskClosable={false}
        getContainer='#app-cad_root'
      >
        <Input
          ref={inputRef}
          onChange={(e) => setSearchTerm(e.target.value)}
          placeholder='搜索'
          value={searchTerm}
          style={{ marginBottom: 16 }}
          prefix={<SearchOutlined />}
        />

        {loading && !selectedRows.length ? (
          <Spin />
        ) : (
          <Tabs items={docTabData} />
        )}
      </Modal>
    </ConfigProvider>
  );
};

export default DocModal;
